const { Op } = require('sequelize');
const { Scam, User, Comment } = require('../models');
const upload = require('../middleware/upload');

// 获取骗子列表
exports.getScams = async (req, res) => {
  try {
    const { page = 1, limit = 10, search = '', sort = 'latest', status = '' } = req.query;
    const offset = (page - 1) * limit;

    const where = {
      status: 'verified'
    };
    
    if (search) {
      where[Op.or] = [
        { phone: { [Op.like]: `%${search}%` } },
        { title: { [Op.like]: `%${search}%` } },
        { description: { [Op.like]: `%${search}%` } }
      ];
    }
    if (status) {
      where.status = status;
    }

    let order = [['createdAt', 'DESC']];
    switch (sort) {
      case 'most_viewed':
        order = [['views', 'DESC']];
        break;
      case 'most_commented':
        order = [['commentCount', 'DESC']];
        break;
      default:
        order = [['createdAt', 'DESC']];
    }

    const { count, rows } = await Scam.findAndCountAll({
      where,
      include: [
        {
          model: User,
          as: 'author',
          attributes: ['id', 'username']
        }
      ],
      order,
      limit: parseInt(limit),
      offset: parseInt(offset)
    });

    const scams = rows.map(scam => ({
      ...scam.toJSON(),
      phoneNumber: scam.phone // 添加 phoneNumber 字段以匹配前端
    }));

    res.json({
      data: scams,
      total: count,
      currentPage: parseInt(page),
      totalPages: Math.ceil(count / limit)
    });
  } catch (error) {
    res.status(500).json({
      message: '获取列表失败',
      error: error.message
    });
  }
};

// 获取单个骗子信息
exports.getScam = async (req, res) => {
  try {
    const scam = await Scam.findByPk(req.params.id, {
      include: [
        {
          model: User,
          as: 'author',
          attributes: ['id', 'username']
        },
        {
          model: Comment,
          as: 'comments',
          include: [
            {
              model: User,
              as: 'author',
              attributes: ['id', 'username']
            }
          ],
          required: false,
          order: [['createdAt', 'DESC']]
        }
      ]
    });

    if (!scam) {
      return res.status(404).json({
        message: '信息不存在'
      });
    }

    // 增加浏览量
    await scam.increment('views');

    // 添加 phoneNumber 字段以匹配前端
    const scamData = {
      ...scam.toJSON(),
      phoneNumber: scam.phone
    };

    res.json(scamData);
  } catch (error) {
    res.status(500).json({
      message: '获取信息失败',
      error: error.message
    });
  }
};

// 创建骗子信息
exports.createScam = async (req, res) => {
  try {
    const { title, phone, description } = req.body;
    const evidence = req.files ? req.files.map(file => file.path) : [];

    const scam = await Scam.create({
      title,
      phone,
      description,
      evidence,
      userId: req.user.id
    });

    res.status(201).json({
      message: '发布成功',
      scam
    });
  } catch (error) {
    res.status(500).json({
      message: '发布失败',
      error: error.message
    });
  }
};

// 更新骗子信息
exports.updateScam = async (req, res) => {
  try {
    const scam = await Scam.findByPk(req.params.id);

    if (!scam) {
      return res.status(404).json({
        message: '信息不存在'
      });
    }

    // 检查权限
    if (scam.userId !== req.user.id && req.user.role !== 'admin') {
      return res.status(403).json({
        message: '没有权限修改此信息'
      });
    }

    const { title, phone, description, status } = req.body;
    const evidence = req.files ? req.files.map(file => file.path) : scam.evidence;

    await scam.update({
      title,
      phone,
      description,
      evidence,
      status: req.user.role === 'admin' ? status : scam.status
    });

    res.json({
      message: '更新成功',
      scam
    });
  } catch (error) {
    res.status(500).json({
      message: '更新失败',
      error: error.message
    });
  }
};

// 删除骗子信息
exports.deleteScam = async (req, res) => {
  try {
    const scam = await Scam.findByPk(req.params.id);

    if (!scam) {
      return res.status(404).json({
        message: '信息不存在'
      });
    }

    // 检查权限
    if (scam.userId !== req.user.id && req.user.role !== 'admin') {
      return res.status(403).json({
        message: '没有权限删除此信息'
      });
    }

    await scam.destroy();

    res.json({
      message: '删除成功'
    });
  } catch (error) {
    res.status(500).json({
      message: '删除失败',
      error: error.message
    });
  }
}; 